﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.ComponentModel;
using System.Threading;

namespace MP3Scrambler
{
    public class MP3Files
    {
        private string directory;
        private object[,] fileData;

        public void setDirectory(string d)
        {
            this.directory = d;
            this.scanDirectory("mp3");
        }

        private void scanDirectory(string fileType)
        {
            string[] contents = Directory.GetFiles(this.directory, "*." + fileType);
            this.sortFolderContents(ref contents);
            this.fileData = new object[contents.Length, 5];

            Random r = new Random();
            DateTime start = new DateTime(2005, 1, 1);
            int range = ((TimeSpan)(DateTime.Today - start)).Days;
            int rangeS = 24 * 60 * 60;
            
            int i = 0;
            foreach(string c in contents){
                this.fileData[i, 0] = c;
                this.fileData[i, 1] = Path.GetFileName(c);

                string noExt = this.fileData[i, 1].ToString().Substring(0, this.fileData[i, 1].ToString().Length - 4);
                string[] splitPlus = noExt.Split('+');

                this.fileData[i, 2] = splitPlus[0] + "+" + r.Next(rangeS) + ".mp3";
                this.fileData[i, 3] = File.GetCreationTime(c);
                this.fileData[i, 4] = start.AddDays(r.Next(range)).AddSeconds(r.Next(rangeS));
                i++;
            }
        }

        private void sortFolderContents(ref string[] contents)
        {
            CreationComparer cCompare = new CreationComparer();
            Array.Sort(contents, cCompare);
        }

        public bool reOrderFiles(BackgroundWorker backroundWorker)
        {
            bool w = true;
            int l = this.fileData.GetLength(0);
            for (int i = 0; i < l; i++)
            {
                try
                {                   
                    File.SetCreationTime((string)this.fileData[i, 0], (DateTime)this.fileData[i, 4]);
                    File.Move((string)this.fileData[i, 0], this.directory+"\\" + (string)this.fileData[i, 2]);
                    int perc = (int)(((float)i / (float)l) * 100);
                    backroundWorker.ReportProgress(perc);
                }
                catch (Exception ex)
                {
                    w = false;
                }
            }

            return w;
        }

        public object[,] getFileData()
        {
            return this.fileData;
        }
    }

    class CreationComparer : IComparer<Object>
    {
        public int Compare(object fileA, object fileB)
        {
            DateTime f1 = File.GetCreationTime((string)fileA);
            DateTime f2 = File.GetCreationTime((string)fileB);

            return DateTime.Compare(f1, f2);
        }
    }
}
